package cn.ljy.authority.service.impl;

import cn.ljy.authority.dao.mapper.SysDictItemMapper;
import cn.ljy.authority.dao.mapper.SysDictMapper;
import cn.ljy.authority.model.SysDict;
import cn.ljy.authority.model.SysDictItem;
import cn.ljy.authority.model.query.SysDictItemQuery;
import cn.ljy.authority.model.query.SysDictQuery;
import cn.ljy.authority.service.SysDictService;
import cn.ljy.common.exception.model.MyWebException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Service
//@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor= MyRollBackException.class)
@Validated//表示开启sprint的校检框架，会自动扫描方法里的@Valid（@Valid注解一般写在接口即可）
@Slf4j
public class ISysDictService extends IBaseService<SysDict, SysDictQuery> implements SysDictService {

    @Autowired
    private SysDictMapper sysDictMapper;
    @Autowired
    private SysDictItemMapper sysDictItemMapper;

    @Override
    protected void beforeGet(Serializable id) {

    }


    @Override
    protected void beforeUpdate(SysDict sysDict) {
        //判断名字是否重名
        if(sysDictMapper.countByNameAndIdNot(sysDict.getName(),sysDict.getId())>0){
            throw new MyWebException("编辑失败：字典名已存在");
        }
    }

    @Override
    protected void beforeSave(SysDict sysDict) {
        //判断名字是否重名
        if(sysDictMapper.countByName(sysDict.getName())>0){
            throw new MyWebException("编辑失败：字典名已存在");
        }
    }

    @Override
    protected void beforeDelete(Serializable[] ids) {
        List<SysDictItem> items=new ArrayList<>();
        for(Serializable id:ids) {
            // 获取该字典下的所有列表项
            SysDictItemQuery sysDictItemQuery=new SysDictItemQuery();
            sysDictItemQuery.setSysDict(new SysDict(Long.valueOf(id.toString())));
            items.addAll(sysDictItemMapper.findAll(sysDictItemQuery));
        }
        sysDictItemMapper.deleteAllIn(items);
    }
}
